<template>
  <el-select
    v-model="current_field"
    :placeholder="placeholder"
    clearable
    filterable
    remote
    :disabled="disabled"
    :remote-method="search"
    :loading="loading"
    loading-text="正在搜索讲师"
    no-data-text="无相关讲师"
    :style="style"
    @change="$emit('update:value', current_field)"
    @focus="eventFocus"
  >
    <el-option v-for="option in selectOptions" :key="option.value" :value="option.value" :label="option.title" />
  </el-select>
</template>
<script>
export default {
  props: {
    value: {
      type: String,
      default: ''
    },
    args: {
      type: Object,
      required: true,
      default: _ => {
        return {};
      }
    },
    formDatas: {
      type: Object,
      required: true,
      default: _ => {
        return {};
      }
    }
  },
  data() {
    return {
      current_field: this.value,
      current_args: this.args,
      mhm_id: this.args.mhm_id,
      loading: false,
      selectOptions: [
        {
          value: this.value,
          title: this.formDatas.teacher_name
        }
      ]
    };
  },
  computed: {
    placeholder() {
      return this.mhm_id ? '输入讲师姓名、手机号或身份证号搜索' : '请选择机构';
    },
    disabled() {
      return !this.mhm_id;
    },
    style() {
      return this.current_args.css ? this.current_args.css : {};
    }
  },
  watch: {
    value: {
      handler(now, old) {
        this.current_field = now;
      }
    },
    'formDatas.mhm_id': {
      handler(now, old) {
        this.mhm_id = now;
        this.$emit('update:value', '');
      }
    },
    'args.mhm_id': {
      handler(now, old) {
        this.mhm_id = now;
      }
    },
    'formDatas.teacher_name': {
      handler(now, old) {
        this.selectOptions = [
          {
            value: this.value,
            title: now
          }
        ];
      }
    }
  },
  methods: {
    eventFocus: function() {
      this.search();
    },
    search: function(keyword) {
      this.loading = true;
      this.$http.get(
        '/user/admin/teacher/search',
        {
          keyword: keyword,
          mhm_id: this.mhm_id
        },
        response => {
          this.selectOptions = response.data;
          if (!keyword && this.selectOptions.length == 0) {
            this.$message.warning('当前机构无讲师，请先添加');
          }
          this.loading = false;
        },
        _ => {
          this.selectOptions = [];
          this.$message.error('搜索讲师失败，请重试');
          this.loading = false;
        },
        false
      );
    }
  }
};
</script>
<style scoped="scoped" lang="scss">
.el-select {
  width: 288px;
}
</style>
